package com.example.lib_leancloud

import cn.leancloud.LCObject
import com.example.lib_leancloud.model.Adv
import com.example.lib_leancloud.model.Chart
import com.example.lib_leancloud.model.Music
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlin.random.Random

/**
 * 管理LeanCloud中的所有操作
 * 获取广告图 获取榜单 获取榜单中的音乐
 */
class LeanCloudManager private constructor(){//私有化构造函数
    private var advertisementList: List<Adv> = emptyList()
    private var chartList: List<Chart> = emptyList()

    //单例
    companion object{
        val instance = LeanCloudManager()
    }

    /*
    查询榜单信息
     */
    fun loadCharts(callback: (LeanCloudManager, List<Chart>) -> Unit = { _, _ ->}){
        CoroutineScope(Dispatchers.IO).launch {
            val query = LCObject.getQuery(Chart::class.java)
            val results = query.find()
            chartList = results

            withContext(Dispatchers.Main) {
                callback(this@LeanCloudManager,chartList)
            }
        }
    }

    /**
     * 查询某个榜单下的歌曲
     */
    fun loadMusics(chartId:String,callback: (List<Music>) -> Unit = {}){
        CoroutineScope(Dispatchers.IO).launch {
            val query = LCObject.getQuery(Music::class.java)
            //查询music表中的chart_id为chartId的数据
            query.whereEqualTo("chart_id",chartId)
            val results = query.find()

            withContext(Dispatchers.Main) {
                callback(results)
            }
        }
    }


    /*
    外部通过调用这个方法发起下载的动作
     */
    fun loadAdv(callback: (LeanCloudManager, List<Adv>) -> Unit = {_,_ ->}){
        CoroutineScope(Dispatchers.IO).launch {
            //查询广告表
            //创建查询对象LCQuery
            val query = LCObject.getQuery(Adv::class.java)
            val results = query.find()
            advertisementList = results

            withContext(Dispatchers.Main) {
                callback(this@LeanCloudManager,advertisementList)
            }
        }
    }

    /**
     * 获取一个广告对象
     */
    fun getRandomAdv(): Adv{
        val index = Random.nextInt(advertisementList.size)
        return advertisementList[index]
    }
}